﻿using LdtDataEngin.ModuleDetail.BaseModule;
using LdtDataEngin.ModuleDetail.BaseModule.MultiFack;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.ElmentModel;
using LdtJudge.DataEngine.Model.Personnel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.OptimzeMode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.CaseCauseElementExtr
{
    /// <summary>
    /// 证据要素提取
    /// </summary>
    public class EvidInfoElement : FactElementBaseClass
    {
        #region 基础信息
        /// <summary>
        /// 案由信息
        /// </summary>
        public CaseCauseModel SYS_CaseCause { get; set; }
        /// <summary>
        /// 父节点信息
        /// </summary>
        public CaseCauseModel mSYS_CaseCause { get; set; }
        /// <summary>
        /// 要素合并配置，条件
        /// </summary>
        //public List<OptimizationXmlConfigModel> opconfigList { get; set; }
        public List<OptimizeSameNodeXML> opconfigList { get; set; }
        #endregion
        /// <summary>
        /// 证据要素处理
        /// </summary>
        /// <param name="onExtract"></param>
        /// <param name="nodeModelList"></param>
        /// <returns></returns>
        public override XmlNode ExtElementXmlParse(OnExtractComplete onExtract, NodeModelList nodeModelList)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = _dataContext };
            List<NodeModel> listNodeModel = new List<NodeModel>();
            CommElementRegexCode commElementRegexCode = new CommElementRegexCode();
            commElementRegexCode.CaseType = _dataContext.DataLayerAns.CaseType;
            commElementRegexCode.TextType = 0;
            //当SourceCode为借款担保合同时，取本值，其他取法庭笔录的值
         
            if(_dataContext.DataLayerAns.SourceCode.ToLower().Equals("mscourtrecord"))
            {
                commElementRegexCode.SourceCode = "ProofElementExtract";
            }
            else
            {
                commElementRegexCode.SourceCode = _dataContext.DataLayerAns.SourceCode;
            }
            PersonElementEntity personElementEntity = base.GroupParseTextDic.Keys.FirstOrDefault();
            try
            {
                var GroupParseTextDics = LoadEvidData(base.CaseID, personElementEntity.SP_Name, personElementEntity.SuitDegreeID);
                foreach (var item in GroupParseTextDics)
                {
                    commElementRegexCode.PargarphCode = item.Key.ParagraphCode.ToLower();
                    commElementRegexCode.Purpose = ExtractType.evid;
                    Dictionary<string, List<string>> ParagraphTemp = new Dictionary<string, List<string>>();
                    ParagraphTemp.Add(item.Key.ParagraphCode.ToLower(), new List<string>() { item.Value });
                    messagelist = new List<string>();
                    List<NodeModel> listNodeModelTemp = new List<NodeModel>();
                    ///清空源数据
                    base.OriginalTextNodeList.Clear();
                    base.LoadeNodeModel(null, mSYS_CaseCause, listNodeModelTemp, item.Value, ParagraphTemp, commElementRegexCode);
                    if (listNodeModelTemp.Count > 0)
                    {
                        ///将提取一次的数据进行存入到提取前数据集合中
                        nodeModelList.BeforeMergerListModels.AddRange(base.OriginalTextNodeList);
                        nodeModelList.BeforeMergerListModels.AddRange(listNodeModelTemp);
                    }
                    onExtract(commElementRegexCode.Purpose, listNodeModelTemp, messagelist, item.Key);
                    NodeModelList nodeModel = new NodeModelList();
                    List<NodeModelList> nodeModelLists = new List<NodeModelList>();
                    if (listNodeModelTemp.Count > 0)
                    {
                        nodeModel.BeforeMergerListModels.AddRange(base.OriginalTextNodeList);
                        nodeModel.BeforeMergerListModels.AddRange(listNodeModelTemp);
                    }
                    nodeModelLists.Add(nodeModel);
                    if (nodeModel.BeforeMergerListModels.Count > 0)
                    {
                        List<DataModel> dataModelList = AnalysisElementSaveXML(nodeModelLists);
                        XmlDocument xml1 = XmlUtility.DataModelByXml(dataModelList);
                        dataModelList = xmlUtilCommon.GetXMLByDataModelBack(xml1).dataModelList;
                        dataModelList.FirstOrDefault(a => a.ID == _dataContext.DataLayerAns.CaseCausesList[0].CC_ID).ParentId = item.Key.ElementID;
                        string uid = Snowflake.Instance().GetId().ToString();
                        dataModelList.FirstOrDefault(a => a.ID == _dataContext.DataLayerAns.CaseCausesList[0].CC_ID).ID = uid;
                        foreach (DataModel data in dataModelList.Where(a => a.ParentId == _dataContext.DataLayerAns.CaseCausesList[0].CC_ID))
                        {
                            data.ParentId = uid;
                        }

                        _dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.AddRange(dataModelList);

                        XmlDocument xmlDocumentp = XmlUtility.DataModelByXml(_dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList);
                        _dataContext.DataLayerAns.AnalysisResultsXml = xmlDocumentp;
                        XmlDocument xml2 = XmlUtility.DataModelByXml(_dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList);
                        listNodeModel.AddRange(listNodeModelTemp);
                    }


                }
                ModelXmlHandle modelXmlHandle = new ModelXmlHandle();
                modelXmlHandle.dataContext = _dataContext;
                XmlNode xml = modelXmlHandle.ModelToXmlPro(SYS_CaseCause, listNodeModel);
                return xml;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
        ///// <summary>
        ///// 要素提取入口
        ///// </summary>
        ///// <returns></returns>
        //public override List<NodeModel> ExtElementParse(OnExtractComplete onExtract, NodeModelList nodeModelList)
        //{
        //    List<NodeModel> listNodeModel = new List<NodeModel>();
        //    CommElementRegexCode commElementRegexCode = new CommElementRegexCode();
        //    commElementRegexCode.CaseType = _dataContext.DataLayerAns.CaseType;
        //    commElementRegexCode.SourceCode = "ProofElementExtract";
        //    commElementRegexCode.TextType = 0;
        //    PersonElementEntity personElementEntity = base.GroupParseTextDic.Keys.FirstOrDefault();
        //    try
        //    {
        //        var GroupParseTextDics = LoadEvidData(base.CaseID, personElementEntity.SP_Name, personElementEntity.SuitDegreeID);
        //        foreach (var item in GroupParseTextDics)
        //        {
        //            commElementRegexCode.PargarphCode = item.Key.ParagraphCode;
        //            commElementRegexCode.Purpose = ExtractType.evid;
        //            Dictionary<string, List<string>> ParagraphTemp = new Dictionary<string, List<string>>();
        //            ParagraphTemp.Add(item.Key.ParagraphCode.ToLower(), new List<string>() { item.Value });
        //            messagelist = new List<string>();
        //            List<NodeModel> listNodeModelTemp = new List<NodeModel>();
        //            ///清空源数据
        //            base.OriginalTextNodeList.Clear();
        //            base.LoadeNodeModel(null, mSYS_CaseCause, listNodeModelTemp, item.Value, ParagraphTemp, commElementRegexCode);
        //            if (listNodeModelTemp.Count > 0)
        //            {
        //                ///将提取一次的数据进行存入到提取前数据集合中
        //                nodeModelList.BeforeMergerListModels.AddRange(base.OriginalTextNodeList);
        //                nodeModelList.BeforeMergerListModels.AddRange(listNodeModelTemp);
        //            }
        //            onExtract(commElementRegexCode.Purpose, listNodeModelTemp, messagelist, item.Key);
        //            listNodeModel.AddRange(listNodeModelTemp);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception(ex.ToString());
        //    }
        //    return listNodeModel;
        //}
        #region 加载证据所需的内容
        /// <summary>
        /// 加载证据数据
        /// </summary>
        /// <param name="caseID">案件ID</param>
        /// <param name="sp_name">人员名称</param>
        /// <param name="suitDegreeID">人员诉讼地位</param>
        /// <returns></returns>
        private Dictionary<PersonElementEntity, string> LoadEvidData(string caseID, string sp_name, string suitDegreeID)
        {
            Dictionary<PersonElementEntity, string> EvidData = new Dictionary<PersonElementEntity, string>();
            if (_dataContext.DataLayerAns.AnalysisResultsDataModel != null && _dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.Count > 0)
            {
                if (suitDegreeID == "89")
                {
                    List<DataModel> dataEvidList = _dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.Where(a => a.XmlPath.IndexOf(@"证据/详情") > -1).ToList();
                    if (dataEvidList.FirstOrDefault(a => a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名" && b.sourceList.FirstOrDefault(c => c.IsCheck == "1") != null &&
                    b.sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == sp_name) != null) != null)
                    {
                        dataEvidList = dataEvidList.Where(a => a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名" && b.sourceList.FirstOrDefault(c => c.IsCheck == "1") != null &&
                        b.sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == sp_name) != null).ToList();
                        foreach (DataModel evidData in dataEvidList)
                        {
                            DataModel modelRoot = _dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.FirstOrDefault(a => a.ParentId == evidData.ID);
                            if (modelRoot != null)
                            {
                                //案件条目数据
                                List<DataModel> evid_detailed = _dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.Where(a => a.ParentId == modelRoot.ID).ToList();
                                foreach (DataModel detaiedEvid in evid_detailed)
                                {
                                    PersonElementEntity personElementEntity = new PersonElementEntity();
                                    personElementEntity.CaseID = caseID;
                                    personElementEntity.IsConfirm = "1";
                                    if (_dataContext.DataLayerAns.SourceCode.ToLower().Equals("ws010003831"))
                                    {
                                        personElementEntity.ParagraphCode = "WS010003831";
                                    }
                                    else if (_dataContext.DataLayerAns.SourceCode.ToLower().Equals("ws010000507"))
                                    {
                                        personElementEntity.ParagraphCode = "b1_lossdetail_content";
                                    }
                                    else if (_dataContext.DataLayerAns.SourceCode.ToLower().Equals("ws010003662"))
                                    {
                                        personElementEntity.ParagraphCode = "ws010003662";
                                    }
                                    else
                                    {
                                        personElementEntity.ParagraphCode = "plaintiffproof";
                                    }
                                    //personElementEntity.ParseText = HttpHelp.DeCodeBase64new(65001, detaiedEvid.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").OriginalText);
                                    personElementEntity.ParseText = detaiedEvid.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                    personElementEntity.SED_ID = "";
                                    personElementEntity.ShortName = "";
                                    personElementEntity.SourceID = _dataContext.DataLayerAns.SourceCode.ToLower();
                                    personElementEntity.SP_Name = sp_name;
                                    personElementEntity.SuitDegreeID = suitDegreeID;
                                    personElementEntity.ElementID = detaiedEvid.ID;
                                    //EvidData.Add(personElementEntity, HttpHelp.DeCodeBase64new(65001,detaiedEvid.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").OriginalText));
                                    EvidData.Add(personElementEntity, detaiedEvid.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue);
                                }
                            }
                            else
                            {

                            }

                        }
                    }
                }
                if (suitDegreeID == "90")
                {
                    List<DataModel> dataEvidList = _dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.Where(a => a.XmlPath.IndexOf(@"证据/详情") > -1).ToList();

                    dataEvidList = dataEvidList.Where(a => a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名" && b.sourceList.FirstOrDefault(c => c.IsCheck == "1") != null &&
                    b.sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == sp_name) != null).ToList();
                    foreach (DataModel evidData in dataEvidList)
                    {
                        //案件条目数据
                        List<DataModel> evid_detailed = _dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.Where(a => a.ParentId == evidData.ID).ToList();
                        foreach (DataModel detaiedEvid in evid_detailed)
                        {
                            PersonElementEntity personElementEntity = new PersonElementEntity();
                            personElementEntity.CaseID = caseID;
                            personElementEntity.IsConfirm = "1";
                            personElementEntity.ParagraphCode = "defendantproof";
                            //personElementEntity.ParseText = HttpHelp.DeCodeBase64new(65001,detaiedEvid.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").OriginalText);
                            personElementEntity.ParseText = detaiedEvid.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                            personElementEntity.SED_ID = "";
                            personElementEntity.ShortName = "";
                            personElementEntity.SourceID = _dataContext.DataLayerAns.SourceCode.ToLower();
                            personElementEntity.SP_Name = sp_name;
                            personElementEntity.SuitDegreeID = suitDegreeID;
                            personElementEntity.ElementID = detaiedEvid.ID;
                            //EvidData.Add(personElementEntity, HttpHelp.DeCodeBase64new(65001,detaiedEvid.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").OriginalText));
                            EvidData.Add(personElementEntity, detaiedEvid.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue);
                        }
                    }
                }

            }
            else
            {
                _dataContext.InteractiveShow.LogShow("证据内容加载失败，案由要素未分析出结果");
            }

            return EvidData;
        }

        #endregion
    }
}
